package com.xysoft;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ServiceLocator {
	public static class Initializer implements ServletContextListener {
		public void contextInitialized(ServletContextEvent sce) {
			// 设置Spring的应用上下文
			APPLICATION_CONTEXT = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
		}

		public void contextDestroyed(ServletContextEvent sce) {
		}
	}

	public static ApplicationContext APPLICATION_CONTEXT;

	public static Object getService(String serviceId) {
		return APPLICATION_CONTEXT.getBean(serviceId);
	}

	public static <T> T getService(Class<T> serviceType) {
		return APPLICATION_CONTEXT.getBean(serviceType);
	}

	public static <T> T getService(String serviceId, Class<T> serviceType) {
		return APPLICATION_CONTEXT.getBean(serviceId, serviceType);
	}

}
